package p07_bean的几种初始化和销毁方法;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ConfigurationClassPostProcessor;
import org.springframework.context.support.GenericApplicationContext;

import javax.annotation.PreDestroy;

/**
 * 目前，已知的bean销毁方法有三种
 *      1.使用@PreDestroy注解
 *      2.继承DisposableBean实现destroy方法
 *      3.配置类中通过@Bean(destroyMethod = "destroy方法")指定
 *    以上三种销毁方法依次执行
 */
public class _2_Destroy {

    public static void main(String[] args) {
        GenericApplicationContext context = new GenericApplicationContext();
        context.registerBean(ConfigurationClassPostProcessor.class);
        context.registerBean(CommonAnnotationBeanPostProcessor.class);

        context.registerBean("config", _2_Destroy.Config.class);
        context.refresh();
        context.close();
    }


    @Configuration
    static class Config {
        @Bean(destroyMethod = "destroy2")
        public MyBean myBean() {
            return new MyBean();
        }
    }

    static class MyBean implements DisposableBean {
        @PreDestroy
        public void destroy1() {
            System.out.println("destroy1...");
        }

        @Override
        public void destroy() throws Exception {
            System.out.println("destroy2...");
        }

        public void destroy2() {
            System.out.println("destroy3...");
        }
    }
}
